package com.wfh.picture.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wfh.picture.exception.BusinessException;
import com.wfh.picture.exception.ErrorCode;
import com.wfh.picture.exception.ThrowUtils;
import com.wfh.picture.manager.sharding.DynamicShardingManager;
import com.wfh.picture.mapper.SpaceMapper;
import com.wfh.picture.model.dto.space.SpaceAddRequest;
import com.wfh.picture.model.dto.space.SpaceQueryRequest;
import com.wfh.picture.model.entity.Space;
import com.wfh.picture.model.entity.SpaceUser;
import com.wfh.picture.model.entity.User;
import com.wfh.picture.model.enums.SpaceLevelEnum;
import com.wfh.picture.model.enums.SpaceRoleEnum;
import com.wfh.picture.model.enums.SpaceTypeEnum;
import com.wfh.picture.model.vo.SpaceVO;
import com.wfh.picture.model.vo.UserVO;
import com.wfh.picture.service.SpaceService;
import com.wfh.picture.service.SpaceUserService;
import com.wfh.picture.service.UserService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
* @author lenovo
* @description 针对表【space(空间)】的数据库操作Service实现
* @createDate 2025-05-12 20:49:43
*/
@Service
public class SpaceServiceImpl extends ServiceImpl<SpaceMapper, Space>
    implements SpaceService {


    @Resource
    private UserService userService;

    @Resource
    private TransactionTemplate transactionTemplate;


    @Resource
    @Lazy
    private SpaceUserService spaceUserService;


    @Resource
    private RedissonClient redissonClient;


    @Resource
    @Lazy
    private DynamicShardingManager dynamicShardingManager;

    /**
     * 获取封装类
     * @param space
     * @param request
     * @return
     */
    @Override
    public SpaceVO getSpaceVO(Space space, HttpServletRequest request) {
        // 对象转封装类
        SpaceVO spaceVO = SpaceVO.objToVo(space);
        // 关联查询用户信息
        Long userId = space.getUserId();
        if (userId != null && userId > 0) {
            User user = userService.getById(userId);
            UserVO userVO = userService.getUserVO(user);
            spaceVO.setUser(userVO);
        }
        return spaceVO;
    }

    /**
     * 创建空间
     * @param spaceAddRequest
     * @param loginUser
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public long addSpace(SpaceAddRequest spaceAddRequest, User loginUser) {
        // 填充信息
        Space space = new Space();
        BeanUtils.copyProperties(spaceAddRequest, space);
        // 校验参数
        if (space.getSpaceName() == null){
            space.setSpaceName("默认空间");
        }
        if (space.getSpaceLevel() == null){
            space.setSpaceLevel(SpaceLevelEnum.COMMON.getValue());
        }
        if (space.getSpaceType() == null){
            space.setSpaceType(SpaceTypeEnum.PRIVATE.getValue());
        }
        this.fillParams(space);
        // 权限校验
        validSpace(space, true);
        Long id = loginUser.getId();
        space.setUserId(id);
        if (SpaceLevelEnum.COMMON.getValue() != space.getSpaceLevel() && !userService.isAdmin(loginUser)){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR.ordinal(), "无权限");
        }
        String lock = String.valueOf(id).intern();
        // 获取分布式锁
        RLock clientLock = redissonClient.getLock(lock);
        // 一个用户只能创建一个私有空间、以及一个团队空间
        // 获取代理对象
        SpaceService spaceService = (SpaceService) AopContext.currentProxy();
        // 尝试获取锁
        boolean tryLock = false;
        try {
            tryLock = clientLock.tryLock(10, 100, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            log.error("获取锁被打断");
        }
        boolean finalTryLock = tryLock;
        Long execute = transactionTemplate.execute(status -> {
            if (finalTryLock){
                try {
                    // 判断是否有空间
                    boolean exists = spaceService.lambdaQuery()
                            .eq(Space::getUserId, id)
                            .eq(Space::getSpaceType, space.getSpaceType())
                            .exists();
                    ThrowUtils.throwIf(exists, ErrorCode.PARAMS_ERROR, "每个用户每一个类型的空间只能创建一个");

                    // 创建空间
                    boolean save = spaceService.save(space);
                    if (!save) {
                        throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间创建失败");
                    }
                    // 创建成功后，如果是团队空间，关联新增团队成员记录
                    if (SpaceTypeEnum.TEAM.getValue() == space.getSpaceType()) {
                        SpaceUser spaceUser = new SpaceUser();
                        spaceUser.setSpaceId(space.getId());
                        spaceUser.setUserId(id);
                        spaceUser.setSpaceRole(SpaceRoleEnum.ADMIN.getValue());
                        boolean save1 = spaceUserService.save(spaceUser);
                        ThrowUtils.throwIf(!save1, ErrorCode.OPERATION_ERROR, "空间团队成员创建失败");
                    }
                    // 创建分表
                    dynamicShardingManager.createSpacePictureTable(space);
                    // 返回写入数据的id
                    return space.getId();
                } catch (BusinessException e) {
                    throw new RuntimeException(e);
                } finally {
                    clientLock.unlock();
                }
            }else {
                log.error("尝试获取锁失败");
            }
            return space.getId();
        });
        return execute;
    }

    /**
     * 校验空间
     * @param space
     * @param add
     */
    @Override
    public void validSpace(Space space, boolean add) {
        ThrowUtils.throwIf(space == null, ErrorCode.PARAMS_ERROR);
        // 从对象中取值
        Long id = space.getId();
        String spaceName = space.getSpaceName();
        Integer spaceLevel = space.getSpaceLevel();
        Integer spaceType = space.getSpaceType();
        SpaceTypeEnum spaceTypeEnum = SpaceTypeEnum.getEnumByValue(spaceType);
        SpaceLevelEnum enumByValue = SpaceLevelEnum.getEnumByValue(spaceLevel);
        // 创建时候校验
        if (add){
            if (StrUtil.isBlank(spaceName)){
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间名称不能为空");
            }
            if (spaceLevel == null){
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间级别不能为空");
            }
            if (spaceTypeEnum == null){
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间类型不存在");
            }
        }else {
            // 修改数据时，id 不能为空，有参数则校验
            ThrowUtils.throwIf(ObjUtil.isNull(id), ErrorCode.PARAMS_ERROR, "id 不能为空");
        }
        if (StrUtil.isNotBlank(spaceName) && spaceName.length() > 30) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间名称不能大于30");
        }
        if (ObjUtil.isNotEmpty(spaceLevel) && enumByValue == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间级别不存在");
        }
        if (ObjUtil.isNotEmpty(spaceType) && spaceTypeEnum == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间类型不存在");
        }
    }

    /**
     * 分页获取封装类
     * @param spacePage
     * @param request
     * @return
     */
    @Override
    public Page<SpaceVO> getSpaceVOPage(Page<Space> spacePage, HttpServletRequest request) {
        List<Space> spaceList = spacePage.getRecords();
        Page<SpaceVO> spaceVOPage = new Page<>(spacePage.getCurrent(), spacePage.getSize(), spacePage.getTotal());
        if (CollUtil.isEmpty(spaceList)) {
            return spaceVOPage;
        }
        // 对象列表 => 封装对象列表
        List<SpaceVO> spaceVOList = spaceList.stream().map(SpaceVO::objToVo).collect(Collectors.toList());
        // 1. 关联查询用户信息
        Set<Long> userIdSet = spaceList.stream().map(Space::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 2. 填充信息
        spaceVOList.forEach(spaceVO -> {
            Long userId = spaceVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            spaceVO.setUser(userService.getUserVO(user));
        });
        spaceVOPage.setRecords(spaceVOList);
        return spaceVOPage;
    }

    /**
     * 获取去查询对象
     * @param spaceQueryRequest
     * @return
     */
    @Override
    public LambdaQueryWrapper<Space> getQueryWrapper(SpaceQueryRequest spaceQueryRequest) {
        Long id = spaceQueryRequest.getId();
        String name = spaceQueryRequest.getSpaceName();
        Integer spaceLevel = spaceQueryRequest.getSpaceLevel();
        Long userId = spaceQueryRequest.getUserId();
        Integer spaceType = spaceQueryRequest.getSpaceType();
        LambdaQueryWrapper<Space> lambdaQueryWrapper = new LambdaQueryWrapper<Space>();
        lambdaQueryWrapper.eq(ObjUtil.isNotEmpty(id), Space::getId, id)
                .eq(ObjUtil.isNotEmpty(userId), Space::getUserId, userId)
                .eq(ObjUtil.isNotEmpty(spaceType), Space::getSpaceType, spaceType)
                .like(StrUtil.isNotBlank(name), Space::getSpaceName, name)
                .eq(ObjUtil.isNotEmpty(spaceLevel), Space::getSpaceLevel, spaceLevel);

        return lambdaQueryWrapper;
    }

    /**
     * 填充参数
     * @param space
     */
    @Override
    public void fillParams(Space space) {
        SpaceLevelEnum enumByValue = SpaceLevelEnum.getEnumByValue(space.getSpaceLevel());
        if (enumByValue != null){
            long maxCount = enumByValue.getMaxCount();
            long maxSize = enumByValue.getMaxSize();
            if (space.getMaxSize() == null){
                space.setMaxSize(maxSize);
            }
            if (space.getMaxCount() == null){
                space.setMaxCount(maxCount);
            }
        }
    }
}




